<?php

namespace app\achievement\controller;

use app\common\model\CustomerModel;
use app\common\model\InvitationRecord;
use app\common\model\OaWorkersModel;
use app\common\service\CommonService;
use app\common\service\ExcelService;
use app\common\model\OaAchievementWorkersModel;
use app\common\model\Operation;
use app\common\model\Administrative;
use app\common\model\Engineers;
use app\common\model\OaWorkersUpgradeLog;
use think\Db;
use app\common\model\OaDealerApplyModel;
use app\common\model\OaDealerApplyLogModel;
use app\common\model\OaWorkersContractModel;

/**
 * Class Test
 * @package app\achievement\controller
 */
class Employee extends Base
{
    // 初始化构造方法
    protected $oaAchievementWorkersModel;
    protected $oaWorkersModel;
    protected $operationModel;
    protected $administrativeModel;
    protected $engineersModel;
    protected $oaWorkersUpgradeLog;
    protected $oaDealerApplyModel;
    protected $oaDealerApplyLogModel;
    protected $customerModel;
    protected $oaWorkersContractModel;
    protected $invitationRecordModel;

    public function __construct()
    {
        parent::__construct();
        $this->oaAchievementWorkersModel = new OaAchievementWorkersModel();
        $this->oaWorkersModel = new OaWorkersModel();
        $this->operationModel = new Operation();
        $this->administrativeModel = new Administrative();
        $this->engineersModel = new Engineers();
        $this->oaWorkersUpgradeLog = new OaWorkersUpgradeLog();
        $this->oaDealerApplyModel = new OaDealerApplyModel();
        $this->oaDealerApplyLogModel = new OaDealerApplyLogModel();
        $this->customerModel = new CustomerModel();
        $this->oaWorkersContractModel = new OaWorkersContractModel();
        $this->invitationRecordModel = new InvitationRecord();

    }

    // 员工列表（市场推广管理）
    public function index()
    {
        //获取当前用户权限
        $is_admin = session($this->set['db_name'] . 'is_admin');
        if (!$is_admin) {
            $rule = session($this->set['db_name'] . 'rule');
            //限制划拨
            $tempMoneyTransfer = false;
            if (!empty($rule)) {
                $rule = explode(',', $rule);
                if (in_array('322', $rule)) {
                    $tempMoneyTransfer = true;
                }
            }
        } else {
            $tempMoneyTransfer = true;
        }

        $this->assign('tempMoneyTransfer', $tempMoneyTransfer);
        return $this->fetch();
    }

    // 员工编辑
    public function edit()
    {
        $id = input('id');
        $this->assign('id', $id);
        $is_admin = session($this->set['db_name'] . 'is_admin');
        if (!$is_admin) {
            //获取当前用户权限
            $rule = session($this->set['db_name'] . 'rule');
            //限制
            $editMoney = false;
            $edit = false;
            if (!empty($rule)) {
                $rule = explode(',', $rule);
                if (in_array('327', $rule)) {
                    $editMoney = true;
                }
                if (in_array('328', $rule)) {
                    $edit = true;
                }
            }
        } else {
            $editMoney = true;
            $edit = true;
        }

        $this->assign('editMoney', $editMoney);
        $this->assign('edit', $edit);
        // 调用视图
        return $this->fetch();
    }

    // 市场推广账户变动记录
    public function fundsRecord()
    {
        $id = input('id');
        $this->assign('id', $id);
        // 调用视图
        return $this->fetch();
    }

    // 下属关系结构图
    public function structure()
    {
        $id = input('id');
        $this->assign('id', $id);
        return $this->fetch();
    }

    // 市场推广申请列表
    public function apply()
    {
        $is_admin = session($this->set['db_name'] . 'is_admin');
        if (!$is_admin) {
            $rule = session($this->set['db_name'] . 'rule');
            //限制
            $examine = 0;
            if (!empty($rule)) {
                $rule = explode(',', $rule);
                if (in_array('308', $rule)) {
                    $examine = 1;
                }
            }
        } else {
            $examine = 1;
        }
        $this->assign('examine', $examine);
        return $this->fetch();
    }

    public function apply_detail()
    {
        $param = input('param.');
        if (empty($param['id'])) {
            return false;
        }
        $data = $this->oaDealerApplyModel->getOne(['id' => $param['id']]);
        $data['front_idcard_pic'] = config('qi_niu_url') . $data['front_idcard_pic'];
        $data['back_idcard_pic'] = config('qi_niu_url') . $data['back_idcard_pic'];
        $data['apply_status_desc'] = config('dealer_apply_status')[$data['apply_status']];
        $data['parent'] = [];
        //查询推荐人
        if (!empty($data['referee'])) {
            $data['parent'] = $this->customerModel->getOne(['user_id' => $data['referee']], [], 'telphone,account');
        }
        //是否签合同
        $data['sign_contract'] = 1;
        $data['contract_content'] = '';
        $data['sign_contract_status'] = '';
        if (!empty($data['workers_id'])) {
            $contract = $this->oaWorkersContractModel->getOne(['workers_id' => $data['workers_id']], 'status,content');
            if (!empty($contract)) {
                $data['sign_contract_status'] = $contract['status'];
                $data['contract_content'] = empty($contract['content']) ? '' : config('qi_niu_url') . $contract['content'];
            }
        }
        //轨迹
        $log = $this->oaDealerApplyLogModel->getAll(['dealer_apply_id' => $param['id']]);
        if (!empty($log)) {
            foreach ($log as $k => $v) {
                $log[$k]['add_time'] = date('m月d日 H:i:s', $v['add_time']);
            }
        }
        $this->assign('log', $log);
        $this->assign('data', $data);
        return $this->fetch();
    }

    //开会奖惩记录
    public function meeting()
    {
        return $this->fetch();
    }

    //新增开会奖惩记录
    public function add_meeting()
    {
        return $this->fetch();
    }

    // 导入名单
    public function importMember()
    {
        $file = $this->request->file('file');
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/meeting_member');
            if ($info) {
                $file_path = ROOT_PATH . 'public' . DS . 'uploads/meeting_member' . DS . $info->getSaveName();
                if (!file_exists($file_path)) {
                    returnJsonAdmin(-1003, '文件不存在，请重新上传');
                }
                $array = ExcelService::readExcel($file_path);
                unset($array[1]);
                unset($array[2]);
                // 操作数据
                if (empty($array)) {
                    returnJsonAdmin(-1003, '导入数据为空');
                }
                $arr = [];
                foreach ($array as $key => &$value) {
                    if (empty($value['B']) || empty($value['C'])) {
                        continue;
                    }
                    $item['account'] = $value['B'];
                    $item['telphone'] = $value['C'];
                    $arr[] = $item;
                }
                returnJson(1000, "上传成功", $arr);
            } else {
                // 上传失败获取错误信息
                returnJson(-1003, '上传文件失败');
            }
        }
    }

    //业绩考核
    public function inspect()
    {
        return $this->fetch();
    }

    //上传纸质合同
    public function uploads()
    {
        $id = input('id');

        $this->assign('id', $id);
        return $this->fetch();

    }

    //查看纸质合同
    public function lists()
    {
        $user_id = input('user_id');
        //本地路径
        $local_url = DS . 'uploads/images/';


        $this->assign('user_id', $user_id);
        $this->assign('local_url', $local_url);
        return $this->fetch();

    }

    //推广升级
    public function workers_upgrade()
    {
        if (request()->isAjax()) {
            //接收参数
            $param = input('post.');
            if (empty($param['workers_id'])) {
                returnJson(0, "请选择市场推广");
            }
            if (empty($param['position_id'])) {
                returnJson(0, "请选择升级职位");
            }
            //查询市场推广信息
            $workers_info = $this->oaWorkersModel->getOne(['workers_id' => $param['workers_id'], 'is_delete' => 0], 'workers_id,position');
            if (empty($workers_info)) {
                returnJson(0, "推广信息数据错误");
            }
            if ($workers_info['position'] == 4) {
                returnJson(0, "该推广属于省级推广了");
            }
            //判断同一级别不能升
            if ($workers_info['position'] == $param['position_id']) {
                returnJson(0, "该推广属于同一级别");
            }

            Db::startTrans();  // 开启事务
            try {
                $this->oaWorkersModel->edit(['workers_id' => $workers_info['workers_id']], ['position' => $param['position_id'], 'position_change_mode' => 2]);
                //添加记录
                $add_log = [
                    'workers_id' => $workers_info['workers_id'],
                    'change_mode' => 2,
                    'before_upgrade_grade' => $workers_info['position'],
                    'after_upgrade' => $param['position_id'],
                    'create_time' => time(),
                    'remarks' => $param['remarks'] ?? '',
                ];
                $this->oaWorkersUpgradeLog->add($add_log);
                Db::commit();
                returnJson(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback(); // 事务回滚
                returnJson(0, '操作失败' . $e->getMessage());
            }
        }
        //获取市场推广信息
        $where['position'] = ['NOT IN', [4]];
        $where['is_delete'] = 0;
        $workers = $this->oaWorkersModel->getAll($where, [], 1, -1, 'workers_id,user_id,workers_name,position');
        if (!empty($workers)) {
            foreach ($workers as $k => $v) {
                $workers[$k]['workers_position'] = config('spread_position')[$v['position']];
            }
        }
        //获取职位
        $workers_position = config('spread_position');

        $this->assign('workers_position', $workers_position);
        $this->assign('workers', $workers);
        return $this->fetch();

    }


    //获取职位-----废弃
    public function getPosition($position_id)
    {
        switch ($position_id) {
            case 1;
                $workers_position = '普通';
                break;
            case 2:
                $workers_position = '区级';
                break;
            case 3:
                $workers_position = '市级';
                break;
            case 4:
                $workers_position = '省级';
                break;
            default:
                $workers_position = '未知';
        }
        return $workers_position;
    }

    //根据业绩表获取员工信息 -----废弃
    public function getWorkerInfo($where = [])
    {
        //获取推广信息
        $data = $this->oaAchievementWorkersModel->getAll($where, '*');

        if (!empty($data)) {
            foreach ($data as $k => $v) {
                if ($v['role'] == 1) {
                    //市场推广
                    $workers = $this->oaWorkersModel->getOne(['workers_id' => $v['workers_id']], 'workers_id,workers_name');
                    $data[$k]['name'] = $workers['workers_name'];
                    $data[$k]['role'] = '市场推广';
                } else if ($v['role'] == 2) {
                    //工程
                    $engineers = $this->engineersModel->getOne(['engineers_id' => $v['workers_id']], 'engineers_id,engineers_name,engineers_phone');
                    $data[$k]['name'] = $engineers['engineers_name'];
                    $data[$k]['role'] = '工程';
                } else if ($v['role'] == 3) {
                    //区域承包商
                    if ($v['workers_position'] == 2) {//区级
                        $administratives = $this->administrativeModel->getOne(['a_id' => $v['workers_id']], 'a_id,name,phone');
                        $data[$k]['name'] = $administratives['name'];
                        $data[$k]['role'] = '区级承包商';
                    } else if (in_array($v['workers_position'], [3, 4])) {
                        $operation_user = $this->operationModel->getOne(['o_id' => $v['workers_id']], 'o_id,name,phone');
                        $data[$k]['name'] = $operation_user['name'];

                        $operation_info = $this->operationModel->findOne(['o_id' => $v['workers_id']], 'o_id,pid');
                        if (empty($operation_info['pid'])) {
                            $data[$k]['role'] = '省级承包商';
                        } else {
                            $data[$k]['role'] = '市级承包商';
                        }
                    }

                }
                $data[$k]['position'] = $this->getPosition($v['workers_position']);
            }
        }
        return $data;
    }

    public function trajectory()
    {
        $this->assign('id', input('id'));
        return $this->fetch();
    }

    //导入市场推广
    public function importOaWorkers()
    {
        $file = $this->request->file('file');
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads/oa_wokers');
            if ($info) {
                $file_path = ROOT_PATH . 'public' . DS . 'uploads/oa_wokers' . DS . $info->getSaveName();
                if (!file_exists($file_path)) {
                    returnJsonAdmin(-1003, '文件不存在，请重新上传');
                }
                $array = ExcelService::readExcel($file_path);
                unset($array[1]);
                // 操作数据
                if (empty($array)) {
                    returnJsonAdmin(-1003, '导入数据为空');
                }
                foreach ($array as $key => $value) {
                    if (empty($value['C'])) {
                        continue;
                    }
                    $this->addWorkers($value);
                }
                returnJson(1000, "上传成功", []);
            } else {
                // 上传失败获取错误信息
                returnJson(-1003, '上传文件失败');
            }
        }
    }

    //生成市场推广信息
    public function addWorkers($param)
    {

        Db::startTrans();  // 开启事务
        try {
            //创建用户
            $user_info = $this->addUser(['telphone' => $param['C'], 'name' => $param['B'], 'source' => $param['E']]);
            //生成市场推广
            $need_sign = $param['F'] == '是' ? 1 : 0;
            $workers_id = $this->addWorker(['user_id' => $user_info['user_id'], 'source' => $user_info['source'], 'name' => $user_info['realname'], 'telphone' => $user_info['telphone'], 'account' => $user_info['account'], 'position' => $param['D'], 'need_sign' => $need_sign]);
            //生成申请记录
            $this->addDealerApply(['user_id' => $user_info['user_id'], 'source' => $user_info['source'], 'workers_id' => $workers_id, 'name' => $user_info['realname'], 'telphone' => $user_info['telphone']]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback(); // 事务回滚
        }
    }

    //创建用户
    public function addUser($param)
    {
        //推荐人
        $pid_info = $this->customerModel->getOne(['telphone' => $param['source'], 'is_delete' => 0], [], 'user_id');
        if (empty($pid_info)) {
            return false;
        } else {
            $add_data['source'] = $pid_info['user_id'];
        }
        //本人
        $user_info = $this->customerModel->getOne(['telphone' => $param['telphone'], 'is_delete' => 0], [], 'user_id,telphone,source,realname,account');
        if (empty($user_info)) {
            $add_data['uuid'] = create_uuid();
            $add_data['telphone'] = $param['telphone'];
            $add_data['account'] = CommonService::createSn('oven_user_no', '', 1);
            $add_data['password'] = md5(substr($param['telphone'], -6));
            $add_data['user_belong_to_company'] = 1;
            $add_data['realname'] = $param['name'];
            $add_data['source_is_default'] = 1;
            $add_data['is_delete'] = 0;
            $add_data['is_auth'] = 1;
            $add_data['is_dealer'] = 1;
            $add_data['user_role'] = 2;
            $user_id = $this->customerModel->add($add_data);
            $this->addInviteRecord(['user_id' => $user_id, 'pid' => $add_data['source']]);
            $add_data['user_id'] = $user_id;
            return $add_data;
        } else {
            return $user_info;
        }
    }

    //添加邀请记录
    public function addInviteRecord($param)
    {
        //判断是否已经存在记录
        $info = $this->invitationRecordModel->getOne(['user_id' => $param['user_id'], 'pid' => $param['pid'], 'status' => ['neq', 3]], [], 'invite_id');
        if (!empty($info)) {
            return true;
        }
        $data['user_id'] = $param['user_id'];
        $data['pid'] = $param['pid'];
        $data['create_time'] = time();
        $data['user_openid'] = '';
        $data['status'] = 2;
        $data['way'] = 2;
        return $this->invitationRecordModel->add($data);

    }

    //生成市场推广
    public function addWorker($param)
    {
        $info = $this->oaWorkersModel->getOne(['user_id' => $param['user_id']], 'workers_id');
        if (!empty($info)) {
            return $info['workers_id'];
        }
        $position = ['普通市场推广' => 1, '区级市场推广' => 2, '市级市场推广' => 3, '省级市场推广' => 4, '市场助理' => 7, '市场总监' => 8];
        $add_data['user_id'] = $param['user_id'];
        $add_data['position'] = $position[$param['position']];
        $add_data['position_change_mode'] = 1;
        $add_data['workers_name'] = $param['name'];
        $add_data['workers_password'] = md5(substr($param['telphone'], -6));
        $add_data['workers_phone'] = $param['telphone'];
        $add_data['workers_number'] = $param['account'];
        $add_data['workers_entry_time'] = time();
        $add_data['workers_push_people'] = $param['source'];
        $add_data['add_time'] = time();
        $workers_id = $this->oaWorkersModel->add($add_data);
        $contract_data['workers_id'] = $workers_id;
        $contract_data['contract_no'] = CommonService::createSn("oven_workers_contract", "", 3);
        $contract_data['second_party_name'] = $param['name'];
        $contract_data['second_party_idcard'] = '';
        $contract_data['second_party_address'] = '';
        $contract_data['second_party_telphone'] = $param['telphone'];
        $contract_data['status'] = $param['need_sign'] == 1 ? 1 : 2;
        $contract_data['create_time'] = time();
        $this->oaWorkersContractModel->add($contract_data);
        return $workers_id;


    }

    //生成市场推广申请记录
    public function addDealerApply($param)
    {
        $add_data['user_id'] = $param['user_id'];
        $add_data['company_id'] = 1;
        $add_data['workers_id'] = $param['workers_id'];
        $add_data['username'] = $param['name'];
        $add_data['phone'] = $param['telphone'];
        $add_data['referee'] = $param['source'];
        $add_data['referee_is_default'] = 1;
        $add_data['reason'] = '线下数据导入';
        $add_data['apply_status'] = 2;
        $add_data['apply_time'] = time();
        $add_data['handle_time'] = time();
        $add_data['add_time'] = time();
        $add_data['source'] = 2;
        $dealer_apply_id = $this->oaDealerApplyModel->add($add_data);
        $log['dealer_apply_id'] = $dealer_apply_id;
        $log['type'] = 2;
        $log['operation_type'] = 3;
        $log['add_time'] = time();
        $log['admin_remark'] = '后台导入申请数据';
        $this->oaDealerApplyLogModel->add($log);
        return $dealer_apply_id;
    }


}
